// pages/pack/pack.js
var mqtt = require('../../utils/mqtt.min.js')
var client = null
var app=getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        booklist: [],
        show: false,
        pubTopic: 'XingHuan/Shelf_Signal',    //发布主题
        inventory:"",
        pick_num:"",
        bookshelfInfo:""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        await this.getuserbook()
        this.connectMq()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
      
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
      client.end(); // 断开 MQTT 连接
      console.log("MQTT服务器断开连接");
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    //获取openid

    //获取已购买的书籍
    async getuserbook() {
        var that = this
        const result=await wx.p.request({
          url: app.globalData.url+'/pack/getuserbook',
          method:'GET',
          data:{
            uid:app.globalData.userInfo.uid
          }
        })
        that.setData({
          booklist:result.data.data
        })
    },
    async showPopup(event) {
        var that = this
        const random=await wx.p.request({
          url:app.globalData.url+"/pack/getRandomNum",
          method:"GET",
          data:{
            inventory:event.currentTarget.dataset.index
          }
        })
        wx.showModal({
            title: '取件码',
            content: random.data.data,
            showCancel: false,
            success(res) {
                that.setData({
                  inventory:event.currentTarget.dataset.index,
                  pick_num:random.data.data
                })
                if (res.confirm) {
                    console.log('用户点击确定')
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
        // that.re_t_or_f()
        // console.log(event.currentTarget.dataset.index)
    },
    async onepick(event) {
        var that = this
        var pick_num=event.currentTarget.dataset.index
        var list=[]
        var id=''
        client.publish(that.data.pubTopic,pick_num)
        console.log('取件成功')
        //需要更改取件时间，清掉这个index
        this.data.booklist.forEach(book=>{
          const keys = Object.keys(book);
          const values = Object.values(book);
          if (keys!=pick_num) {
            list.push(book)
          }else{
            console.log(values);
            id=values[0].id
          }
        })
        this.setData({
          booklist:list
        })
        //我觉得这里是需要得到mqtt响应，响应结束才正式的删除
        const result=await wx.p.request({
          method:"GET",
          url:app.globalData.url+"/pack/updatePickupTime",
          data:{
            id:id
          }
        })
    },
    connectMq() {
        var that = this // 连接选项
        const options = {
            // 认证信息 按自己需求填写
            clientId: 'XingHuan_1',
            port: '8084',
            username: 'XingHuan_1', //服务器用户名             
            password: 'XingHuan', //服务器密码
        }
        client = mqtt.connect('wxs://ma0a8495.ala.cn-hangzhou.emqxsl.cn:8084/mqtt', options)
        client.on('connect', (e) => {
            console.log('服务器连接成功')
            client.subscribe('XingHuan/XingHuan_2', {
                qos: 0
            }, function (err) {
                if (!err) {
                    
                    
                }
            })
        })
        client.on('message', function (topic, message) {
            console.log('收到' + message.toString())
        })
        client.on('error', (error) => {
            console.log('连接失败', error)
        })
    },
//释放书柜的标志位
    re_t_or_f(){
        var that = this
        var index = that.data.index
        const db = wx.cloud.database()
        return new Promise((reject,resolve)=>{
            db.collection('bookcase_num').where({
                case_num:that.data.booklist[index].case_num
            }).update({
                data:{
                    use:false
                },
                success(res){
                    reject(res)
                }
            })
        })
        // console.log(that.data.booklist[index].case_num)
        // console.log(index)
    },
    async seachLocation(e){
      var that=this
      const Location=await wx.p.request({
        url:app.globalData.url+"/pack/getlocal",
        method:"GET",
        data:{
          inventory:e.currentTarget.dataset.index
        }
      })
      this.setData({
        bookshelfInfo:Location.data.data
      })
      wx.openLocation({
          latitude: Number(that.data.bookshelfInfo.shelflatitude),
          longitude: Number(that.data.bookshelfInfo.shelflongitude),
          name: that.data.bookshelfInfo.shelfName,
          address: that.data.bookshelfInfo.shelfAddress
      })
    }




})